﻿using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 环境样品检测用户控件
    /// 功能：配置测量参数、选择计算方式、执行环境样品辐射比活度计算
    /// </summary>
    public partial class UcEnvSampleCheck : UserControl
    {
        #region 字段定义

        // 基础配置参数
        private int channelCount = AppConfig.ChannelCount;      // 通道数量
        private int inputHeight = 28;                           // 输入框高度
        private List<ChannelData> channelDataList;              // 存储所有通道数据
        private Dictionary<string, UITextBox[]> workConditionControls; // 存储工作条件控件

        // 效率选择（默认使用标准源效率，不再显示选择界面）
        private UIRadioButton rbWorkSourceEfficiency;           // 工作源效率单选按钮（已隐藏）
        private UIRadioButton rbStandardSourceEfficiency;       // 标准源效率单选按钮（已隐藏）

        // 添加控件引用字段
        private UITextBox txtMeasurementCount;
        private UITextBox txtMeasurementTime;
        private UITextBox txtCorrectionFactor;
        private UITextBox[] basicInfoControls; // 基本信息输入框数组
        protected virtual string MeasurementType { get; set; } = "EnvSample";
        #endregion
        #region 测量结果显示
        // 测量类型显示名称映射
        protected static readonly Dictionary<string, string> MeasurementTypeDisplayNames = new Dictionary<string, string>
{
    {"Background", "本底测量"},
    {"WorkingSourceEfficiency", "工作源效率测量"},
    {"StandardSourceEfficiency", "标准源效率测量"},
    {"WaterSample", "水样品测量"},
    {"BioSample", "生物样品测量"},
    {"GasSample", "气体样品测量"},
    {"EnvSample", "环境样品测量"}
};
        // ================================
        // 3. 通用化的查看最新结果方法
        // ================================

        /// <summary>
        /// 查看最新结果按钮点击事件 - 通用版本
        /// 根据组件的测量类型显示对应的最新多轮测量结果
        /// </summary>
        private async void BtnViewLatestResult_Click(object sender, EventArgs e)
        {
            string originalText = "查看最新结果"; // 在方法开始处
            try
            {
                var clickedButton = sender as UIButton;
                string measurementType = clickedButton?.Tag?.ToString() ?? MeasurementType;
                string displayName = GetMeasurementTypeDisplayName(measurementType);

                // 显示加载提示
                originalText = clickedButton?.Text ?? "查看最新结果";
                if (clickedButton != null)
                {
                    clickedButton.Enabled = false;
                    clickedButton.Text = "加载中...";
                }

                // 查找该类型的最新测量数据
                var latestMeasurementData = await FindLatestMeasurementByType(measurementType);

                if (latestMeasurementData == null)
                {
                    UIMessageBox.ShowWarning($"暂无{displayName}结果！\n请先完成{displayName}后再查看结果。");
                    return;
                }

                // 打开MultiRoundResultForm显示结果
                var resultForm = new MultiRoundResultForm(latestMeasurementData);
                resultForm.ShowDialog(this);

                System.Diagnostics.Debug.WriteLine($"已显示{displayName}最新测量结果，测量时间：{latestMeasurementData.StartTime:yyyy-MM-dd HH:mm:ss}");
            }
            catch (Exception ex)
            {
                string displayName = GetMeasurementTypeDisplayName(MeasurementType);
                UIMessageBox.ShowError($"查看{displayName}最新结果失败：{ex.Message}");
                System.Diagnostics.Debug.WriteLine($"查看{displayName}最新结果失败: {ex.Message}");
            }
            finally
            {
                // 恢复按钮状态
                var clickedButton = sender as UIButton;
                if (clickedButton != null)
                {
                    clickedButton.Enabled = true;
                    clickedButton.Text = originalText;
                }
            }
        }

        /// <summary>
        /// 根据测量类型查找最新的测量数据 - 通用方法
        /// </summary>
        /// <param name="measurementType">测量类型（如"WaterSample", "BioSample"等）</param>
        /// <returns>最新的测量数据，如果不存在返回null</returns>
        private async Task<MultiRoundMeasurementData> FindLatestMeasurementByType(string measurementType)
        {
            MultiRoundMeasurementData latestData = null;
            DateTime latestTime = DateTime.MinValue;

            try
            {
                // 遍历所有通道查找指定类型的测量数据
                for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
                {
                    try
                    {
                        var measurementData = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);

                        if (measurementData != null && measurementData.StartTime > latestTime)
                        {
                            latestTime = measurementData.StartTime;
                            latestData = measurementData;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"检查通道 {channelIndex + 1} {measurementType} 数据时出错: {ex.Message}");
                        // 继续检查其他通道
                    }
                }

                // 记录查找结果
                if (latestData != null)
                {
                    string displayName = GetMeasurementTypeDisplayName(measurementType);
                    System.Diagnostics.Debug.WriteLine($"找到最新{displayName}数据：");
                    System.Diagnostics.Debug.WriteLine($"  测量时间: {latestData.StartTime:yyyy-MM-dd HH:mm:ss} - {latestData.EndTime:yyyy-MM-dd HH:mm:ss}");
                    System.Diagnostics.Debug.WriteLine($"  总轮数: {latestData.TotalRounds}");
                    System.Diagnostics.Debug.WriteLine($"  参与通道: {latestData.ChannelResults.Count} 个");
                    System.Diagnostics.Debug.WriteLine($"  测量ID: {latestData.MeasurementId}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"未找到任何{measurementType}测量数据");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"查找最新{measurementType}测量数据失败: {ex.Message}");
                throw;
            }

            return latestData;
        }

        /// <summary>
        /// 获取测量类型的显示名称
        /// </summary>
        /// <param name="measurementType">英文测量类型</param>
        /// <returns>中文显示名称</returns>
        private string GetMeasurementTypeDisplayName(string measurementType)
        {
            return MeasurementTypeDisplayNames.ContainsKey(measurementType)
                ? MeasurementTypeDisplayNames[measurementType]
                : measurementType;
        }
        #endregion
        #region 数据结构定义

        /// <summary>
        /// 环境样品辐射计算结果类
        /// 包含测量和计算的完整信息
        /// </summary>
        public class EnvRadiationCalculationResult
        {
            public double AlphaSpecificActivity { get; set; }    // α比活度 (Bq/kg)
            public double BetaSpecificActivity { get; set; }     // β比活度 (Bq/kg)
            public int ChannelIndex { get; set; }                // 通道索引
            public EfficiencyType EfficiencyType { get; set; }   // 效率类型
            public DateTime MeasurementTime { get; set; }        // 测量时间
            public double SampleMass { get; set; }               // 样品质量 (mg)
            public double AlphaCountRate { get; set; }           // 测量的α计数率
            public double BetaCountRate { get; set; }            // 测量的β计数率
        }

        /// <summary>
        /// 效率类型枚举
        /// </summary>
        public enum EfficiencyType
        {
            WorkSource,     // 工作源效率
            StandardSource  // 标准源效率
        }

        #endregion

        #region 事件定义

        public event Action<int, int> OnMeasurementStarted;             // 测量开始事件
        public event Action<EfficiencyType> OnEfficiencySelectionChanged; // 效率选择变化事件

        #endregion

        #region 构造函数和初始化

        /// <summary>
        /// 构造函数 - 初始化控件和加载数据
        /// </summary>
        public UcEnvSampleCheck()
        {
            InitializeComponent();
            InitializeWorkConditionControls();     // 初始化工作条件控件字典
            LoadChannelData();                     // 加载通道数据

            // 构建界面各个区域
            BuildBasicInfo();                      // 基本信息区域
            BuildSpacer(1);                       // 间隔
            BuildWork();                          // 工作条件区域
            BuildSpacer(3);                       // 间隔
            // BuildEfficiencySelection();           // 效率选择区域（已隐藏，默认使用标准源效率）
            BuildSpacer(5);                       // 间隔
            BuildDuration();                      // 测量时长区域
            BuildSpacer(7, 20);                   // 间隔
            BuildButtons();                       // 按钮区域

            LoadWorkConditionData();              // 加载数据到控件
        }

        /// <summary>
        /// 初始化工作条件控件字典
        /// 为每个参数类型创建对应数量的输入框数组
        /// </summary>
        private void InitializeWorkConditionControls()
        {
            workConditionControls = new Dictionary<string, UITextBox[]>
            {
                ["alphaBackground"] = new UITextBox[channelCount],
                ["betaBackground"] = new UITextBox[channelCount],
                // ["alphaWorkEfficiency"] = new UITextBox[channelCount],  // 已移除工作源效率
                // ["betaWorkEfficiency"] = new UITextBox[channelCount],   // 已移除工作源效率
                ["alphaStandardEfficiency"] = new UITextBox[channelCount],
                ["betaStandardEfficiency"] = new UITextBox[channelCount]
            };

            // 初始化基本信息控件数组 (6个输入框：名称、编号、采样人、采样地点、测量人、样品质量)
            basicInfoControls = new UITextBox[6];
        }

        /// <summary>
        /// 加载通道数据
        /// 从数据管理器加载所有通道的配置信息
        /// </summary>
        private void LoadChannelData()
        {
            try
            {
                channelDataList = ChannelDataManager.LoadAllChannelData();

                // 确保有足够的通道数据，不足的用默认数据填充
                while (channelDataList.Count < channelCount)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = channelDataList.Count });
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载通道数据失败：{ex.Message}");
                // 初始化默认数据
                channelDataList = new List<ChannelData>();
                for (int i = 0; i < channelCount; i++)
                {
                    channelDataList.Add(new ChannelData { ChannelIndex = i });
                }
            }
        }

        /// <summary>
        /// 加载工作条件数据到界面控件
        /// 从通道数据中读取配置值并显示在对应的输入框中
        /// </summary>
        private void LoadWorkConditionData()
        {
            try
            {
                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];
                    var workCondition = channelData.WorkConditions;

                    // 填充各个工作条件数据
                    if (workConditionControls["alphaBackground"][i] != null)
                        workConditionControls["alphaBackground"][i].Text = workCondition.AlphaBackground.ToString("0.######");

                    if (workConditionControls["betaBackground"][i] != null)
                        workConditionControls["betaBackground"][i].Text = workCondition.BetaBackground.ToString("0.######");

                    // 工作源效率已移除
                    // if (workConditionControls["alphaWorkEfficiency"][i] != null)
                    //     workConditionControls["alphaWorkEfficiency"][i].Text = workCondition.AlphaWorkEfficiency.ToString("0.##");
                    //
                    // if (workConditionControls["betaWorkEfficiency"][i] != null)
                    //     workConditionControls["betaWorkEfficiency"][i].Text = workCondition.BetaWorkEfficiency.ToString("0.##");

                    if (workConditionControls["alphaStandardEfficiency"][i] != null)
                        workConditionControls["alphaStandardEfficiency"][i].Text = workCondition.AlphaStandardEfficiency.ToString("0.##");

                    if (workConditionControls["betaStandardEfficiency"][i] != null)
                        workConditionControls["betaStandardEfficiency"][i].Text = workCondition.BetaStandardEfficiency.ToString("0.##");
                }

                // 加载校正系数（使用保存的控件引用）
                if (channelDataList.Count > 0 && txtCorrectionFactor != null)
                {
                    txtCorrectionFactor.Text = channelDataList[0].WorkConditions.CorrectionFactor.ToString("0.##");
                }

                // 加载测量设置（使用保存的控件引用）
                if (channelDataList.Count > 0)
                {
                    var workCondition = channelDataList[0].WorkConditions;
                    if (txtMeasurementCount != null)
                        txtMeasurementCount.Text = workCondition.MeasurementCycle.ToString();
                    if (txtMeasurementTime != null)
                        txtMeasurementTime.Text = workCondition.MeasurementTime.ToString("0.#");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载工作条件数据失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 保存工作条件数据到配置文件（实现双向绑定）
        /// 从界面控件读取数据并保存到配置文件
        /// </summary>
        private bool SaveWorkConditionToConfig()
        {
            try
            {
                // 保存各通道的工作条件数据
                for (int i = 0; i < channelCount; i++)
                {
                    var channelData = channelDataList[i];
                    var workCondition = channelData.WorkConditions;

                    // 从控件读取并保存各个工作条件数据
                    if (workConditionControls["alphaBackground"][i] != null &&
                        double.TryParse(workConditionControls["alphaBackground"][i].Text, out double alphaBackground))
                    {
                        workCondition.AlphaBackground = alphaBackground;
                    }

                    if (workConditionControls["betaBackground"][i] != null &&
                        double.TryParse(workConditionControls["betaBackground"][i].Text, out double betaBackground))
                    {
                        workCondition.BetaBackground = betaBackground;
                    }

                    // 工作源效率已移除
                    // if (workConditionControls["alphaWorkEfficiency"][i] != null &&
                    //     double.TryParse(workConditionControls["alphaWorkEfficiency"][i].Text, out double alphaWorkEff))
                    // {
                    //     workCondition.AlphaWorkEfficiency = alphaWorkEff;
                    // }
                    //
                    // if (workConditionControls["betaWorkEfficiency"][i] != null &&
                    //     double.TryParse(workConditionControls["betaWorkEfficiency"][i].Text, out double betaWorkEff))
                    // {
                    //     workCondition.BetaWorkEfficiency = betaWorkEff;
                    // }

                    if (workConditionControls["alphaStandardEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["alphaStandardEfficiency"][i].Text, out double alphaStdEff))
                    {
                        workCondition.AlphaStandardEfficiency = alphaStdEff;
                    }

                    if (workConditionControls["betaStandardEfficiency"][i] != null &&
                        double.TryParse(workConditionControls["betaStandardEfficiency"][i].Text, out double betaStdEff))
                    {
                        workCondition.BetaStandardEfficiency = betaStdEff;
                    }
                }

                // 保存校正系数（所有通道使用相同值）
                if (txtCorrectionFactor != null &&
                    double.TryParse(txtCorrectionFactor.Text, out double correctionFactor))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.CorrectionFactor = correctionFactor;
                    }
                }

                // 保存测量设置（所有通道使用相同值）
                if (txtMeasurementCount != null &&
                    int.TryParse(txtMeasurementCount.Text, out int measurementCycle))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementCycle = measurementCycle;
                    }
                }

                if (txtMeasurementTime != null &&
                    double.TryParse(txtMeasurementTime.Text, out double measurementTime))
                {
                    for (int i = 0; i < channelCount; i++)
                    {
                        channelDataList[i].WorkConditions.MeasurementTime = measurementTime;
                    }
                }

                // 保存到文件
                bool saved = ChannelDataManager.SaveAllChannelData(channelDataList);

                if (saved && AppConfig.LogPrint == 1)
                {
                    Console.WriteLine("[环境样品检测] 工作条件已保存到配置文件");
                }

                return saved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[环境样品检测] 保存工作条件失败: {ex.Message}");
                return false;
            }
        }

        #endregion

        #region 界面构建方法

        /// <summary>
        /// 构建基本信息输入区域
        /// 包含：名称、编号、采样人、采样地点、测量人、样品质量
        /// </summary>
        private void BuildBasicInfo()
        {
            var group = new UIGroupBox
            {
                Text = "基本信息",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 12, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = 4,
                RowCount = 5,
                Dock = DockStyle.Fill,
                AutoSize = true,
                Padding = new Padding(4)
            };

            int labelWidth = 120;
            int inputWidth = 200;
            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, labelWidth));
            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, inputWidth));
            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, labelWidth));
            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, inputWidth));

            Padding labelMargin = new Padding(0, 6, 0, 6);
            Padding inputMargin = new Padding(0, 6, 12, 6);

            int row = 0;
            int controlIndex = 0;

            // 修改的行添加方法，保存控件引用
            void AddRow(string leftLabel, string rightLabel, string leftText = "", string rightText = "")
            {
                tbl.Controls.Add(new UILabel { Text = leftLabel, TextAlign = ContentAlignment.MiddleRight, Margin = labelMargin, AutoSize = true }, 0, row);

                basicInfoControls[controlIndex] = new UITextBox { Text = leftText, Width = inputWidth, Margin = inputMargin };
                tbl.Controls.Add(basicInfoControls[controlIndex], 1, row);
                controlIndex++;

                tbl.Controls.Add(new UILabel { Text = rightLabel, TextAlign = ContentAlignment.MiddleRight, Margin = labelMargin, AutoSize = true }, 2, row);

                basicInfoControls[controlIndex] = new UITextBox { Text = rightText, Width = inputWidth, Margin = inputMargin };
                tbl.Controls.Add(basicInfoControls[controlIndex], 3, row);
                controlIndex++;

                row++;
            }

            // 添加各行数据
            AddRow("名称：", "编号：",
                   AppConfig.EnvSampleName,
                   AppConfig.EnvSampleNumber);

            AddRow("采样人：", "采样地点：",
                   AppConfig.EnvSampler,
                   AppConfig.EnvSampleLocation);

            AddRow("测量人：", "样品质量mg：",
                   AppConfig.EnvMeasurer,
                   AppConfig.EnvSampleMass.ToString());
            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 0);
        }
        /// <summary>
        /// 构建工作条件设置区域
        /// 包含各通道的本底、效率参数和校正系数
        /// </summary>
        private void BuildWork()
        {
            var group = new UIGroupBox
            {
                Text = "工作条件",
                Dock = DockStyle.Top,
                AutoSize = true,
                Padding = new Padding(8),
                Margin = new Padding(16, 0, 16, 0)
            };

            var tbl = new TableLayoutPanel
            {
                ColumnCount = channelCount + 1,  // 第一列为标签，其余为通道
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            // 设置列样式
            tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 120));  // 标签列
            for (int i = 0; i < channelCount; i++)
                tbl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / channelCount));  // 通道列

            int row = 0;

            // 通道标题行
            tbl.Controls.Add(new UILabel() { Text = "", Dock = DockStyle.Fill }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                tbl.Controls.Add(new UILabel
                {
                    Text = $"通道{i + 1}",
                    Dock = DockStyle.Left,
                    AutoSize = true,
                    Margin = new Padding(6, 0, 0, 0),
                    TextAlign = ContentAlignment.MiddleLeft
                }, i + 1, row);
            }
            row++;

            // 输入框生成方法 - 修改为可编辑
            UITextBox MakeTextBox(string text = "", bool enabled = true, string name = "")
            {
                return new UITextBox
                {
                    Text = text,
                    Width = 70,
                    Dock = DockStyle.Left,
                    Enabled = enabled,
                    Margin = new Padding(6, 4, 0, 4),
                    Name = name,
                    ReadOnly = false,  // 改为可编辑
                    BackColor = Color.White  // 改为白色背景
                };
            }

            // α本底行
            tbl.Controls.Add(new UILabel { Text = "α 本底CPS", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                var textBox = MakeTextBox("0", true, $"alphaBackground_{i}");
                workConditionControls["alphaBackground"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }
            row++;

            // β本底行
            tbl.Controls.Add(new UILabel { Text = "β 本底CPS", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                var textBox = MakeTextBox("0", true, $"betaBackground_{i}");
                workConditionControls["betaBackground"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }
            row++;

            // α工作源效率行（已移除）
            // tbl.Controls.Add(new UILabel { Text = "α 工作源效率", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            // for (int i = 0; i < channelCount; i++)
            // {
            //     var textBox = MakeTextBox("0.80", true, $"alphaWorkEfficiency_{i}");  // 默认80%
            //     workConditionControls["alphaWorkEfficiency"][i] = textBox;
            //     tbl.Controls.Add(textBox, i + 1, row);
            // }
            // row++;

            // β工作源效率行（已移除）
            // tbl.Controls.Add(new UILabel { Text = "β 工作源效率", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            // for (int i = 0; i < channelCount; i++)
            // {
            //     var textBox = MakeTextBox("0.83", true, $"betaWorkEfficiency_{i}");   // 默认83%
            //     workConditionControls["betaWorkEfficiency"][i] = textBox;
            //     tbl.Controls.Add(textBox, i + 1, row);
            // }
            // row++;

            // α标准源效率行
            tbl.Controls.Add(new UILabel { Text = "α 标准源效率", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                var textBox = MakeTextBox("0.85", true, $"alphaStandardEfficiency_{i}"); // 默认85%
                workConditionControls["alphaStandardEfficiency"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }
            row++;

            // β标准源效率行
            tbl.Controls.Add(new UILabel { Text = "β 标准源效率", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);
            for (int i = 0; i < channelCount; i++)
            {
                var textBox = MakeTextBox("0.92", true, $"betaStandardEfficiency_{i}");  // 默认92%
                workConditionControls["betaStandardEfficiency"][i] = textBox;
                tbl.Controls.Add(textBox, i + 1, row);
            }
            row++;

            // 校正系数K行（保存控件引用）
            tbl.Controls.Add(new UILabel { Text = "校正系数 K", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleRight }, 0, row);

            txtCorrectionFactor = MakeTextBox("1.00", true, "txtCorrectionFactor");
            tbl.Controls.Add(txtCorrectionFactor, 1, row);

            // 添加这两行关键代码
            group.Controls.Add(tbl);
            this.outerLayout.Controls.Add(group, 0, 2);
        }

        /// <summary>
        /// 构建效率选择区域
        /// 让用户选择使用工作源效率还是标准源效率进行计算
        /// </summary>
        private void BuildEfficiencySelection()
        {
            var group = new UIGroupBox
            {
                Text = "计算方式选择",
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(12),
                Margin = new Padding(16, 8, 16, 0)
            };

            var flowPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,
                Padding = new Padding(10, 8, 10, 8)
            };

            // 提示标签
            var lblPrompt = new UILabel
            {
                Text = "请选择用于计算的效率类型：",
                AutoSize = true,
                Font = new Font("微软雅黑", 10F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 158, 255),
                Margin = new Padding(0, 5, 20, 5)
            };

            // 工作源效率单选按钮（默认选中）
            rbWorkSourceEfficiency = new UIRadioButton
            {
                Text = "使用工作源效率",
                AutoSize = true,
                Checked = true,
                Font = new Font("微软雅黑", 9F),
                ForeColor = Color.FromArgb(48, 48, 48),
                Margin = new Padding(0, 5, 30, 5),
                Name = "rbWorkSourceEfficiency"
            };

            // 标准源效率单选按钮
            rbStandardSourceEfficiency = new UIRadioButton
            {
                Text = "使用标准源效率",
                AutoSize = true,
                Checked = false,
                Font = new Font("微软雅黑", 9F),
                ForeColor = Color.FromArgb(48, 48, 48),
                Margin = new Padding(0, 5, 0, 5),
                Name = "rbStandardSourceEfficiency"
            };

            // 绑定选择变化事件
            rbWorkSourceEfficiency.CheckedChanged += EfficiencySelection_CheckedChanged;
            rbStandardSourceEfficiency.CheckedChanged += EfficiencySelection_CheckedChanged;

            // 添加控件到流式布局
            flowPanel.Controls.Add(lblPrompt);
            flowPanel.Controls.Add(rbWorkSourceEfficiency);
            flowPanel.Controls.Add(rbStandardSourceEfficiency);

            group.Controls.Add(flowPanel);
            this.outerLayout.Controls.Add(group, 0, 4);
        }

        /// <summary>
        /// 构建测量时长设置区域
        /// 包含测量次数和测量时间设置
        /// </summary>
        private void BuildDuration()
        {
            var group = new UIGroupBox
            {
                Text = "测量时长",
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                Padding = new Padding(12),
                Margin = new Padding(16, 8, 16, 0)
            };

            var table = new TableLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                ColumnCount = 4,
                RowCount = 1,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            // 设置列样式为自适应
            table.ColumnStyles.Clear();
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
            table.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));

            table.RowStyles.Clear();
            table.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            // 测量次数控件
            var lblCount = new UILabel
            {
                Text = "测量次数",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };
            var txtCount = new UITextBox
            {
                Name = "txtMeasurementCount",
                Text = "1",                          // 默认测量1次
                Width = 80,
                Margin = new Padding(0, 2, 24, 2),
                Enabled = false,
                ReadOnly = true,
                BackColor = Color.FromArgb(240, 240, 240),
                Anchor = AnchorStyles.Left
            };

            // 测量时间控件
            var lblTime = new UILabel
            {
                Text = "测量时间(min)",
                AutoSize = true,
                TextAlign = ContentAlignment.MiddleRight,
                Width = 96,
                Margin = new Padding(0, 6, 12, 6)
            };
            var txtTime = new UITextBox
            {
                Name = "txtMeasurementTime",
                Text = "5",                          // 默认测量5分钟
                Width = 80,
                Margin = new Padding(0, 2, 0, 2),
                Enabled = false,
                ReadOnly = true,
                BackColor = Color.FromArgb(240, 240, 240),
                Anchor = AnchorStyles.Left
            };

            // 保存控件引用 - 修改为可编辑
            txtMeasurementCount = new UITextBox
            {
                Name = "txtMeasurementCount",
                Text = "1",
                Width = 80,
                Margin = new Padding(0, 2, 24, 2),
                Enabled = true,  // 改为可用
                ReadOnly = false,  // 改为可编辑
                BackColor = Color.White,  // 改为白色背景
                Anchor = AnchorStyles.Left
            };

            txtMeasurementTime = new UITextBox
            {
                Name = "txtMeasurementTime",
                Text = "5",
                Width = 80,
                Margin = new Padding(0, 2, 0, 2),
                Enabled = true,  // 改为可用
                ReadOnly = false,  // 改为可编辑
                BackColor = Color.White,  // 改为白色背景
                Anchor = AnchorStyles.Left
            };

            // 添加控件到表格
            table.Controls.Add(lblCount, 0, 0);
            table.Controls.Add(txtMeasurementCount, 1, 0);
            table.Controls.Add(lblTime, 2, 0);
            table.Controls.Add(txtMeasurementTime, 3, 0);

            group.Controls.Add(table);
            this.outerLayout.Controls.Add(group, 0, 6);

            // 移除这里的数据加载，转移到LoadWorkConditionData
            group.Height = group.PreferredSize.Height;
        }

        /// <summary>
        /// 构建按钮区域
        /// 包含开始测量和取消按钮
        /// </summary>
        private void BuildButtons()
        {
            panelButtons.AutoSize = true;
            panelButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            panelButtons.Dock = DockStyle.Top;
            panelButtons.Padding = new Padding(0);
            panelButtons.Margin = new Padding(16, 8, 16, 0);

            panelButtons.Controls.Clear();

            var panel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,
                Padding = new Padding(4, 8, 4, 8),
                Margin = new Padding(0)
            };

            // 开始测量按钮
            var btnStartMeasurement = new UIButton
            {
                Text = "开始测量",
                Width = 110,
                Height = 36,
                Margin = new Padding(60, 0, 0, 0)
            };
            btnStartMeasurement.Click += BtnStartMeasurement_Click;

            // 取消按钮
            var btnCancel = new UIButton
            {
                Text = "取消",
                Width = 110,
                Height = 36,
                Margin = new Padding(32, 0, 0, 0)
            };
            btnCancel.Click += BtnCancel_Click;


            // 查看最新结果按钮
            var btnViewLatestResult = new UIButton
            {
                Text = "查看最新结果",
                Width = 130,
                Height = 36,
                Margin = new Padding(20, 0, 0, 0),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Tag = MeasurementType // 使用Tag存储测量类型
            };
            btnViewLatestResult.Click += BtnViewLatestResult_Click;
            panel.Controls.Add(btnViewLatestResult);

            panel.Controls.Add(btnStartMeasurement);
            panel.Controls.Add(btnCancel);

            panelButtons.Controls.Add(panel);
            this.outerLayout.Controls.Add(panelButtons, 0, 8);
        }

        /// <summary>
        /// 构建间隔区域
        /// 用于在界面元素间添加空白间距
        /// </summary>
        private void BuildSpacer(int row, int height = 12)
        {
            var spacer = new Panel { Height = height, Dock = DockStyle.Top, BackColor = Color.Transparent };
            this.outerLayout.Controls.Add(spacer, 0, row);
        }

        #endregion

        #region 事件处理方法

        /// <summary>
        /// 效率选择变化事件处理
        /// 当用户切换效率类型时更新UI状态
        /// </summary>
        private void EfficiencySelection_CheckedChanged(object sender, EventArgs e)
        {
            var radioButton = sender as UIRadioButton;
            if (radioButton == null || !radioButton.Checked) return;

            UpdateEfficiencySelectionUI();                              // 更新界面视觉反馈
            OnEfficiencySelectionChanged?.Invoke(GetSelectedEfficiencyType()); // 触发自定义事件
        }

        /// <summary>
        /// 更新效率选择的UI视觉状态
        /// 高亮选中项，淡化未选中项
        /// </summary>
        private void UpdateEfficiencySelectionUI()
        {
            if (rbWorkSourceEfficiency.Checked)
            {
                rbWorkSourceEfficiency.ForeColor = Color.FromArgb(64, 158, 255);    // 高亮蓝色
                rbStandardSourceEfficiency.ForeColor = Color.FromArgb(140, 140, 140); // 灰色
            }
            else
            {
                rbWorkSourceEfficiency.ForeColor = Color.FromArgb(140, 140, 140);    // 灰色
                rbStandardSourceEfficiency.ForeColor = Color.FromArgb(64, 158, 255); // 高亮蓝色
            }
        }

        /// <summary>
        /// 开始测量按钮点击事件
        /// 验证输入参数并触发测量开始事件
        /// </summary>
        private void BtnStartMeasurement_Click(object sender, EventArgs e)
        {
            try
            {
                // 使用保存的控件引用，而不是查找
                if (txtMeasurementCount == null || txtMeasurementTime == null)
                {
                    UIMessageBox.ShowError("界面控件未正确初始化。");
                    return;
                }

                // 验证输入参数
                if (!int.TryParse(txtMeasurementCount.Text, out int measurementCount) ||
                    !int.TryParse(txtMeasurementTime.Text, out int measurementTime))
                {
                    UIMessageBox.ShowError("请输入有效的数字。");
                    return;
                }

                // 验证基本信息参数
                double sampleMass = GetSampleMass();
                if (sampleMass <= 0)
                {
                    UIMessageBox.ShowError("请确保样品质量大于0。");
                    return;
                }

                // === 新增：保存工作条件到配置文件（实现双向绑定）===
                bool workConditionSaved = SaveWorkConditionToConfig();
                if (!workConditionSaved)
                {
                    var result = MessageBox.Show("工作条件保存失败，是否继续进行测量？",
                                               "保存提示",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                // === 新增：保存基本信息到配置文件 ===
                bool configSaved = SaveBasicInfoToConfig();
                if (!configSaved)
                {
                    // 保存失败，询问用户是否继续
                    var result = MessageBox.Show("配置保存失败，是否继续进行测量？",
                                               "保存提示",
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                    {
                        return;
                    }
                }

                // 获取选择的效率类型并显示确认信息
                var efficiencyType = GetSelectedEfficiencyType();
                // 已默认使用标准源效率，不再显示计算方式
                // var efficiencyTypeText = efficiencyType == EfficiencyType.WorkSource ? "工作源效率" : "标准源效率";

                // 触发测量开始事件
                OnMeasurementStarted?.Invoke(measurementCount, measurementTime);

                string successMessage = $"开始测量：次数 {measurementCount}, 时间 {measurementTime} 分钟";
                if (workConditionSaved && configSaved)
                {
                    successMessage += "\n工作条件和基本信息已保存到配置文件";
                }
                else if (workConditionSaved)
                {
                    successMessage += "\n工作条件已保存到配置文件";
                }
                else if (configSaved)
                {
                    successMessage += "\n基本信息已保存到配置文件";
                }

                UIMessageBox.ShowSuccess(successMessage);
                this.Parent?.Hide();
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"启动测量时发生错误：{ex.Message}");
            }
        }
        /// <summary>
        /// 取消按钮点击事件
        /// 关闭当前窗体
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Parent?.Hide();
        }

        #endregion

        #region 公开方法 - 配置和状态管理

        /// <summary>
        /// 获取当前选择的效率类型
        /// </summary>
        public EfficiencyType GetSelectedEfficiencyType()
        {
            // 默认使用标准源效率（计算方式选择界面已隐藏）
            return EfficiencyType.StandardSource;
        }

        /// <summary>
        /// 设置效率类型选择
        /// </summary>
        public void SetEfficiencyType(EfficiencyType efficiencyType)
        {
            rbWorkSourceEfficiency.Checked = (efficiencyType == EfficiencyType.WorkSource);
            rbStandardSourceEfficiency.Checked = (efficiencyType == EfficiencyType.StandardSource);
            UpdateEfficiencySelectionUI();
        }

        /// <summary>
        /// 获取当前工作条件数据
        /// 从界面控件中读取所有通道的工作条件参数
        /// </summary>
        public Dictionary<int, WorkConditionData> GetCurrentWorkConditions()
        {
            var result = new Dictionary<int, WorkConditionData>();

            for (int i = 0; i < channelCount; i++)
            {
                var workCondition = new WorkConditionData();

                // 解析各项参数，失败时使用默认值0
                if (double.TryParse(workConditionControls["alphaBackground"][i]?.Text, out double alphaBackground))
                    workCondition.AlphaBackground = alphaBackground;

                if (double.TryParse(workConditionControls["betaBackground"][i]?.Text, out double betaBackground))
                    workCondition.BetaBackground = betaBackground;

                if (double.TryParse(workConditionControls["alphaWorkEfficiency"][i]?.Text, out double alphaWorkEff))
                    workCondition.AlphaWorkEfficiency = alphaWorkEff;

                if (double.TryParse(workConditionControls["betaWorkEfficiency"][i]?.Text, out double betaWorkEff))
                    workCondition.BetaWorkEfficiency = betaWorkEff;

                if (double.TryParse(workConditionControls["alphaStandardEfficiency"][i]?.Text, out double alphaStdEff))
                    workCondition.AlphaStandardEfficiency = alphaStdEff;

                if (double.TryParse(workConditionControls["betaStandardEfficiency"][i]?.Text, out double betaStdEff))
                    workCondition.BetaStandardEfficiency = betaStdEff;

                result[i] = workCondition;
            }

            return result;
        }

        /// <summary>
        /// 验证工作条件数据有效性
        /// 检查所有输入框的数据格式是否正确
        /// </summary>
        public bool ValidateWorkConditionData()
        {
            for (int i = 0; i < channelCount; i++)
            {
                foreach (var controlPair in workConditionControls)
                {
                    var textBox = controlPair.Value[i];
                    if (textBox != null && !double.TryParse(textBox.Text, out double value))
                    {
                        UIMessageBox.ShowError($"通道 {i + 1} 的 {controlPair.Key} 数据格式错误");
                        textBox.Focus(); // 聚焦到错误的输入框
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 获取用于计算的效率值
        /// 根据当前选择的效率类型返回对应的效率数据
        /// </summary>
        public Dictionary<int, (double alphaEfficiency, double betaEfficiency)> GetCalculationEfficiencies()
        {
            var result = new Dictionary<int, (double alphaEfficiency, double betaEfficiency)>();
            var efficiencyType = GetSelectedEfficiencyType();

            for (int i = 0; i < channelCount; i++)
            {
                double alphaEff = 0, betaEff = 0;

                if (efficiencyType == EfficiencyType.WorkSource)
                {
                    // 使用工作源效率
                    double.TryParse(workConditionControls["alphaWorkEfficiency"][i]?.Text, out alphaEff);
                    double.TryParse(workConditionControls["betaWorkEfficiency"][i]?.Text, out betaEff);
                }
                else
                {
                    // 使用标准源效率
                    double.TryParse(workConditionControls["alphaStandardEfficiency"][i]?.Text, out alphaEff);
                    double.TryParse(workConditionControls["betaStandardEfficiency"][i]?.Text, out betaEff);
                }

                result[i] = (alphaEff, betaEff);
            }

            return result;
        }

        /// <summary>
        /// 从界面获取基本信息参数
        /// 读取样品质量等基础参数
        /// </summary>
        public double GetSampleMass()
        {
            double sampleMass = 20.0;

            try
            {
                // 使用保存的控件引用直接获取数据
                if (basicInfoControls != null && basicInfoControls.Length >= 6)
                {
                    if (double.TryParse(basicInfoControls[5].Text, out double mass))
                        sampleMass = mass;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取样品质量失败: {ex.Message}");
            }

            return sampleMass;
        }

        /// <summary>
        /// 获取测量参数
        /// 从界面读取测量次数和测量时间
        /// </summary>
        private (int measurementCount, double measurementTime) GetMeasurementParameters()
        {
            int measurementCount = 1;
            double measurementTime = 5.0;

            try
            {
                // 使用保存的控件引用
                if (txtMeasurementCount != null)
                    int.TryParse(txtMeasurementCount.Text, out measurementCount);

                if (txtMeasurementTime != null)
                    double.TryParse(txtMeasurementTime.Text, out measurementTime);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取测量参数失败: {ex.Message}");
            }

            return (measurementCount, measurementTime);
        }
        /// <summary>
        /// 获取样品基本信息
        /// 从界面读取样品的标识和人员信息
        /// </summary>
        private SampleBasicInfo GetSampleBasicInfo()
        {
            var sampleInfo = new SampleBasicInfo();

            try
            {
                // 使用保存的控件引用直接获取数据
                if (basicInfoControls != null && basicInfoControls.Length >= 5)
                {
                    sampleInfo.Name = basicInfoControls[0].Text ?? "";
                    sampleInfo.Number = basicInfoControls[1].Text ?? "";
                    sampleInfo.Sampler = basicInfoControls[2].Text ?? "";
                    sampleInfo.SampleLocation = basicInfoControls[3].Text ?? "";
                    sampleInfo.Measurer = basicInfoControls[4].Text ?? "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取样品基本信息失败: {ex.Message}");
            }

            return sampleInfo;
        }

        #endregion

        #region 核心计算方法

        /// <summary>
        /// 计算所有通道的α和β辐射比活度
        /// 这是主要的计算入口方法，针对环境样品使用质量计算
        /// </summary>
        /// <param name="measuredCountRates">测量计数率 [通道索引] = (α计数率, β计数率)</param>
        /// <param name="sampleMass">样品质量 (mg)</param>
        /// <returns>计算结果列表</returns>
        public List<EnvRadiationCalculationResult> CalculateSpecificActivities(
            Dictionary<int, (double alphaRate, double betaRate)> measuredCountRates,
            double sampleMass)
        {
            var results = new List<EnvRadiationCalculationResult>();
            var efficiencyType = GetSelectedEfficiencyType();          // 获取选择的效率类型
            var efficiencies = GetCalculationEfficiencies();           // 获取计算用的效率值
            var workConditions = GetCurrentWorkConditions();           // 获取工作条件

            // 获取校正系数
            var correctionFactorControl = this.Controls.Find("txtCorrectionFactor", true).FirstOrDefault() as UITextBox;
            double correctionFactor = 1.0;
            if (correctionFactorControl != null)
            {
                double.TryParse(correctionFactorControl.Text, out correctionFactor);
            }

            // 遍历所有测量数据进行计算
            foreach (var measurement in measuredCountRates)
            {
                int channelIndex = measurement.Key;
                var (alphaRate, betaRate) = measurement.Value;

                // 检查必要数据是否存在
                if (!workConditions.ContainsKey(channelIndex) || !efficiencies.ContainsKey(channelIndex))
                    continue;

                var workCondition = workConditions[channelIndex];
                var (alphaEff, betaEff) = efficiencies[channelIndex];

                // 转换效率百分比为小数
                double alphaEfficiency = alphaEff / 100.0;
                double betaEfficiency = betaEff / 100.0;

                // 计算α比活度
                double alphaSpecificActivity = CalculateAlphaSpecificActivity(
                    alphaRate,
                    workCondition.AlphaBackground,
                    sampleMass,
                    alphaEfficiency,
                    correctionFactor
                );

                // 计算β比活度
                double betaSpecificActivity = CalculateBetaSpecificActivity(
                    betaRate,
                    workCondition.BetaBackground,
                    sampleMass,
                    betaEfficiency,
                    correctionFactor
                );

                // 创建并添加计算结果
                results.Add(new EnvRadiationCalculationResult
                {
                    ChannelIndex = channelIndex,
                    AlphaSpecificActivity = alphaSpecificActivity,
                    BetaSpecificActivity = betaSpecificActivity,
                    EfficiencyType = efficiencyType,
                    MeasurementTime = DateTime.Now,
                    SampleMass = sampleMass,
                    AlphaCountRate = alphaRate,
                    BetaCountRate = betaRate
                });
            }

            return results;
        }

        /// <summary>
        /// 计算α辐射比活度
        /// 使用公式：A(α) = (R_s(α) - R_0(α)) / (m × η × K)
        /// </summary>
        /// <param name="measuredRate">R_s(α) - 测量计数率</param>
        /// <param name="backgroundRate">R_0(α) - 本底计数率</param>
        /// <param name="mass">m - 样品质量 (mg)</param>
        /// <param name="efficiency">η - 效率 (小数形式)</param>
        /// <param name="correctionFactor">K - 校正系数</param>
        /// <returns>α辐射比活度 (Bq/kg)</returns>
        private double CalculateAlphaSpecificActivity(
            double measuredRate,
            double backgroundRate,
            double mass,
            double efficiency,
            double correctionFactor
        )
        {
            // 检查除数不为零
            if (mass <= 0 || efficiency <= 0)
                return 0;

            // 质量从mg转换为kg
            double massInKg = mass / 1000000.0; // mg转kg

            // 应用计算公式
            double numerator = measuredRate - backgroundRate;
            double denominator = massInKg * efficiency * correctionFactor;

            return numerator / denominator;
        }

        /// <summary>
        /// 计算β辐射比活度
        /// 使用公式：A(β) = (R_s(β) - R_0(β)) / (m × η × K)
        /// </summary>
        /// <param name="measuredRate">R_s(β) - 测量计数率</param>
        /// <param name="backgroundRate">R_0(β) - 本底计数率</param>
        /// <param name="mass">m - 样品质量 (mg)</param>
        /// <param name="efficiency">η - 效率 (小数形式)</param>
        /// <param name="correctionFactor">K - 校正系数</param>
        /// <returns>β辐射比活度 (Bq/kg)</returns>
        private double CalculateBetaSpecificActivity(
            double measuredRate,
            double backgroundRate,
            double mass,
            double efficiency,
            double correctionFactor
        )
        {
            // 检查除数不为零
            if (mass <= 0 || efficiency <= 0)
                return 0;

            // 质量从mg转换为kg
            double massInKg = mass / 1000000.0; // mg转kg

            // 应用计算公式
            double numerator = measuredRate - backgroundRate;
            double denominator = massInKg * efficiency * correctionFactor;

            return numerator / denominator;
        }

        #endregion

        #region 数据保存和管理方法

        /// <summary>
        /// 将计算结果保存到对应通道的JSON数据中
        /// 保存完整的测量结果信息，包括计算结果和测量参数
        /// </summary>
        public bool SaveCalculationResultsToChannelData(List<EnvRadiationCalculationResult> results)
        {
            try
            {
                // 获取基本信息和测量参数
                var sampleInfo = GetSampleBasicInfo();
                var (measurementCount, measurementTime) = GetMeasurementParameters();

                // 遍历结果并保存到对应通道
                foreach (var result in results)
                {
                    // 获取对应通道的数据
                    var channelData = ChannelDataManager.LoadChannelData(result.ChannelIndex);

                    // 确保MeasurementResults不为null
                    if (channelData.MeasurementResults == null)
                    {
                        channelData.MeasurementResults = new MeasurementResultData();
                    }

                    // 保存环境样品测量结果
                    channelData.MeasurementResults.EnvSampleResult = new EnvSampleMeasurementResult
                    {
                        //AlphaSpecificActivity = result.AlphaSpecificActivity,
                        //BetaSpecificActivity = result.BetaSpecificActivity,
                        //MeasurementTime = result.MeasurementTime,
                        //SampleMass = result.SampleMass,
                        //EfficiencyType = result.EfficiencyType.ToString(),
                        //AlphaCountRate = result.AlphaCountRate,
                        //BetaCountRate = result.BetaCountRate,
                        //MeasurementCycles = measurementCount,
                        //MeasurementDuration = measurementTime,
                        //SampleInfo = sampleInfo
                    };

                    // 更新最后修改时间
                    channelData.LastModified = DateTime.Now;

                    // 保存到JSON文件
                    ChannelDataManager.SaveChannelData(result.ChannelIndex, channelData);

                    System.Diagnostics.Debug.WriteLine($"通道 {result.ChannelIndex + 1} 环境样品测量结果已保存：α={result.AlphaSpecificActivity:F6} Bq/kg, β={result.BetaSpecificActivity:F6} Bq/kg");
                }

                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存计算结果失败: {ex.Message}");
                UIMessageBox.ShowError($"保存计算结果失败：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 执行完整的测量计算并保存结果
        /// 这是外部调用的主要方法，集成了计算和保存功能
        /// </summary>
        /// <param name="measuredCountRates">测量计数率数据</param>
        /// <returns>是否成功</returns>
        public bool PerformCalculationAndSave(Dictionary<int, (double alphaRate, double betaRate)> measuredCountRates)
        {
            try
            {
                // 获取样品质量
                double sampleMass = GetSampleMass();

                // 验证样品质量
                if (sampleMass <= 0)
                {
                    UIMessageBox.ShowError("样品质量必须大于0");
                    return false;
                }

                // 执行辐射比活度计算
                var results = CalculateSpecificActivities(measuredCountRates, sampleMass);

                // 检查计算结果
                if (results.Count == 0)
                {
                    UIMessageBox.ShowWarning("没有有效的计算结果");
                    return false;
                }

                // 保存结果到JSON文件
                bool saveSuccess = SaveCalculationResultsToChannelData(results);

                if (saveSuccess)
                {
                    UIMessageBox.ShowSuccess($"环境样品测量完成，结果已保存到各通道数据中\n共处理 {results.Count} 个通道的数据");
                    return true;
                }
                else
                {
                    UIMessageBox.ShowError("计算完成但保存失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"执行计算和保存时发生错误：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 处理测量完成事件
        /// 当实际测量完成时调用此方法进行数据处理
        /// </summary>
        /// <param name="measuredCountRates">实际测量得到的计数率数据</param>
        public void OnMeasurementCompleted(Dictionary<int, (double alphaRate, double betaRate)> measuredCountRates)
        {
            // 执行计算并保存结果
            bool success = PerformCalculationAndSave(measuredCountRates);

            if (success)
            {
                // 记录成功信息，可以在此触发其他后续操作
                System.Diagnostics.Debug.WriteLine("环境样品测量计算和保存完成");
                // 可以添加更多后续处理，如更新UI、发送通知等
            }
        }

        #endregion

        #region 静态辅助方法

        /// <summary>
        /// 从通道数据中读取环境样品测量结果
        /// 静态方法，可独立调用来查询已保存的结果
        /// </summary>
        /// <param name="channelIndex">通道索引</param>
        /// <returns>环境样品测量结果，如果不存在返回null</returns>
        public static EnvSampleMeasurementResult GetEnvSampleResult(int channelIndex)
        {
            try
            {
                var channelData = ChannelDataManager.LoadChannelData(channelIndex);
                return channelData.MeasurementResults?.EnvSampleResult;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取通道 {channelIndex + 1} 环境样品结果失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 检查指定通道是否有环境样品测量结果
        /// 用于判断通道是否已完成环境样品测量
        /// </summary>
        /// <param name="channelIndex">通道索引</param>
        /// <returns>是否有结果</returns>
        public static bool HasEnvSampleResult(int channelIndex)
        {
            var result = GetEnvSampleResult(channelIndex);
            return result != null && result.MeasurementTime != default(DateTime);
        }

        /// <summary>
        /// 增强版的RefreshData方法 - 同时刷新AppConfig和ChannelData
        /// </summary>
        public void RefreshData()
        {
            try
            {
                // 1. 刷新通道相关数据
                LoadChannelData();
                LoadWorkConditionData();

                // 2. 刷新基本信息数据（从AppConfig）
                LoadBasicInfoFromConfig();

                // 3. 强制刷新界面
                this.Invalidate();
                this.Update();

                System.Diagnostics.Debug.WriteLine("UcEnvSampleCheck 数据和界面已完全刷新");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"刷新数据失败：{ex.Message}");
            }
        }

        #endregion
        #region 计算
        public double GetTestedSampleMass()
        {
            return GetSampleMass();
        }

        public double GetCorrectionFactor()
        {
            double correctionFactor = 1.0;
            if (txtCorrectionFactor != null)
            {
                double.TryParse(txtCorrectionFactor.Text, out correctionFactor);
            }
            return correctionFactor;
        }

        public bool GetUseStandardEfficiency()
        {
            return GetSelectedEfficiencyType() == EfficiencyType.StandardSource;
        }
        #endregion

        #region 配置保存和刷新功能

        /// <summary>
        /// 保存基本信息到AppConfig配置文件
        /// </summary>
        private bool SaveBasicInfoToConfig()
        {
            try
            {
                // 从界面控件获取基本信息
                if (basicInfoControls == null || basicInfoControls.Length < 6)
                {
                    UIMessageBox.ShowError("界面控件未正确初始化");
                    return false;
                }

                string name = basicInfoControls[0].Text ?? "";
                string number = basicInfoControls[1].Text ?? "";
                string sampler = basicInfoControls[2].Text ?? "";
                string location = basicInfoControls[3].Text ?? "";
                string measurer = basicInfoControls[4].Text ?? "";

                // 获取数值参数，解析失败时使用当前配置的默认值
                double sampleMass = AppConfig.EnvSampleMass;
                double.TryParse(basicInfoControls[5].Text, out sampleMass);

                // 保存到配置文件
                bool success = AppConfig.SaveEnvSampleInfo(
                    name, number, sampler, location, measurer, sampleMass
                );

                if (success)
                {
                    System.Diagnostics.Debug.WriteLine("基本信息已保存到配置文件");
                    return true;
                }
                else
                {
                    UIMessageBox.ShowError("保存配置失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"保存基本信息失败：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 从AppConfig重新加载基本信息到界面控件
        /// </summary>
        private void LoadBasicInfoFromConfig()
        {
            try
            {
                if (basicInfoControls == null || basicInfoControls.Length < 6)
                {
                    return;
                }

                // 刷新配置缓存
                AppConfig.RefreshConfiguration();

                // 从配置文件重新加载数据到控件
                basicInfoControls[0].Text = AppConfig.EnvSampleName;
                basicInfoControls[1].Text = AppConfig.EnvSampleNumber;
                basicInfoControls[2].Text = AppConfig.EnvSampler;
                basicInfoControls[3].Text = AppConfig.EnvSampleLocation;
                basicInfoControls[4].Text = AppConfig.EnvMeasurer;
                basicInfoControls[5].Text = AppConfig.EnvSampleMass.ToString();

                System.Diagnostics.Debug.WriteLine("基本信息已从配置文件重新加载");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载基本信息失败: {ex.Message}");
                UIMessageBox.ShowError($"从配置文件加载基本信息失败：{ex.Message}");
            }
        }
        #endregion
    }
}